

package com.hazelcast.map.impl.operation;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.HazelcastInstanceAware;
import com.hazelcast.internal.serialization.Data;
import com.hazelcast.map.EntryProcessor;
import com.hazelcast.map.impl.MapDataSerializerHook;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.spi.impl.operationservice.BackupOperation;

import java.io.IOException;

import static com.hazelcast.map.impl.operation.EntryOperator.operator;

/**
 * @see EntryOperation for Offloadable support.
 */
public class EntryBackupOperation extends KeyBasedMapOperation implements BackupOperation {

    private EntryProcessor entryBackupProcessor;

    public EntryBackupOperation() {
    }

    public EntryBackupOperation(String name, Data dataKey, EntryProcessor entryBackupProcessor) {
        super(name, dataKey);
        this.entryBackupProcessor = entryBackupProcessor;
    }

    @Override
    public void innerBeforeRun() throws Exception {
        super.innerBeforeRun();

        if (entryBackupProcessor instanceof HazelcastInstanceAware aware) {
            HazelcastInstance hazelcastInstance = getNodeEngine().getHazelcastInstance();
            aware.setHazelcastInstance(hazelcastInstance);
        }
    }

    @Override
    protected void runInternal() {
        operator(this, entryBackupProcessor).operateOnKey(dataKey).doPostOperateOps();
    }

    @Override
    protected void readInternal(ObjectDataInput in) throws IOException {
        super.readInternal(in);
        entryBackupProcessor = callWithNamespaceAwareness(in::readObject);
    }

    @Override
    protected void writeInternal(ObjectDataOutput out) throws IOException {
        super.writeInternal(out);
        out.writeObject(entryBackupProcessor);
    }

    @Override
    public int getClassId() {
        return MapDataSerializerHook.ENTRY_BACKUP;
    }
}
